#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import time
from datetime import datetime


class SMSTestClient:
    def __init__(self, base_url="http://localhost:8080"):
        self.base_url = base_url
        self.headers = {
            'Content-Type': 'application/json',
            'User-Agent': 'SMS-Test-Client/1.0'
        }

    def test_health(self):
        """测试健康检查接口"""
        try:
            response = requests.get(f"{self.base_url}/health", headers=self.headers)
            print(f"Health Check - Status Code: {response.status_code}")
            print(f"Response: {response.json()}")
            return response.status_code == 200
        except Exception as e:
            print(f"Health Check Failed: {e}")
            return False

    def send_sms(self, sender, content, receive_time=None):
        """发送短信测试数据"""
        payload = {
            "sender": sender,
            "content": content
        }

        if receive_time:
            payload["receive_time"] = receive_time
        elif receive_time is None:
            # 使用当前时间
            payload["receive_time"] = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

        try:
            response = requests.post(
                f"{self.base_url}/webhook/sms",
                headers=self.headers,
                data=json.dumps(payload)
            )
            print(f"Send SMS - Status Code: {response.status_code}")
            print(f"Request: {payload}")
            print(f"Response: {response.json()}")
            return response.status_code == 201
        except Exception as e:
            print(f"Send SMS Failed: {e}")
            return False

    def test_invalid_request(self):
        """测试无效请求"""
        # 缺少sender参数
        payload1 = {
            "content": "Test content"
        }

        # 缺少content参数
        payload2 = {
            "sender": "1234567890"
        }

        try:
            response1 = requests.post(
                f"{self.base_url}/webhook/sms",
                headers=self.headers,
                data=json.dumps(payload1)
            )
            print(f"Missing sender - Status Code: {response1.status_code}")
            print(f"Response: {response1.json()}")

            response2 = requests.post(
                f"{self.base_url}/webhook/sms",
                headers=self.headers,
                data=json.dumps(payload2)
            )
            print(f"Missing content - Status Code: {response2.status_code}")
            print(f"Response: {response2.json()}")

            return True
        except Exception as e:
            print(f"Invalid Request Test Failed: {e}")
            return False


def main():
    # 创建测试客户端
    client = SMSTestClient("http://localhost:8080")

    print("=== SMS Service Test Script ===\n")

    # 1. 测试健康检查
    print("1. Testing Health Check:")
    if client.test_health():
        print("✓ Health check passed\n")
    else:
        print("✗ Health check failed\n")

    # 2. 测试正常发送短信
    print("2. Testing Normal SMS Sending:")
    client.send_sms(
        sender="13800138000",
        content="这是一条测试短信内容",
        receive_time=datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
    )
    print()

    # 3. 测试不带接收时间的短信
    print("3. Testing SMS without receive_time:")
    client.send_sms(
        sender="13900139000",
        content="这是一条没有指定接收时间的测试短信"
    )
    print()

    # 4. 测试无效请求
    print("4. Testing Invalid Requests:")
    client.test_invalid_request()
    print()

    # 5. 测试批量发送
    print("5. Testing Batch SMS Sending:")
    test_data = [
        {"sender": "13700137001", "content": "第一条批量测试短信"},
        {"sender": "13700137002", "content": "第二条批量测试短信"},
        {"sender": "13700137003", "content": "第三条批量测试短信"}
    ]

    for i, data in enumerate(test_data, 1):
        print(f"Sending test message {i}:")
        client.send_sms(data["sender"], data["content"])
        # 等待1秒避免请求过于频繁
        time.sleep(1)

    print("\n=== Test Completed ===")


if __name__ == "__main__":
    main()
